package lumis.service.portalmanagement.pagetemplate;

import lumis.doui.source.ISourceData;
import lumis.doui.source.Source;
import lumis.doui.source.TabularData;
import lumis.doui.source.postloadprocessor.IPostLoadProcessor;
import lumis.portal.PortalException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.channel.ChannelConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.page.PageConfig;
import lumis.portal.propertybag.Property;
import lumis.portal.propertybag.PropertyBag;
import lumis.util.ITransaction;

import java.util.List;

import org.w3c.dom.Node;

/**
 * Post load processor that loads the extra properties of the page.
 *
 * @version $Revision: 11804 $ $Date: 2010-07-29 10:06:21 -0300 (Thu, 29 Jul 2010) $
 * @since 5.6.0
 */
public class PageTemplatePostLoadProcessor implements IPostLoadProcessor
{
	public void processSource(SessionConfig sessionConfig, Source source, Node parametersNode, ITransaction transaction) throws PortalException
	{
		TabularData tabularData = (TabularData) source.getData();
		for (ISourceData row : tabularData.getRows())
		{
			String id = row.get("pageId", String.class);
			PageConfig page = ManagerFactory.getPageManager().get(sessionConfig, id, transaction);
			PropertyBag propertyBag = ManagerFactory.getPropertyBagManager().get(page.getPropertyBagId());

			// get the inherited layout file
			ChannelConfig parentChannelConfig = ManagerFactory.getChannelManager().get(sessionConfig, page.getChannelId(), transaction);
			int layoutType = ManagerFactory.getChannelManager().getLayoutPagesType(sessionConfig, parentChannelConfig, transaction);
			if(PageConfig.PAGE_LAYOUT_TYPE_LAYOUT_FILE == layoutType)
			{
				String value = parentChannelConfig.getLayoutFilePath();
				if(value != null)
					row.put("inheritedLayoutFile", value);
			}
			
			// get the layout file
			try
			{
				Property localProperty = propertyBag.getLocalProperty(PageConfig.LAYOUT_FILE_PATH_PROPERTY_NAME);
				List<String> defaultValues = localProperty.getDefaultValues();
				if(!defaultValues.isEmpty())
				{
					String value = defaultValues.get(0);
					if(value != null)
						row.put("currentLayoutFile", value);
				}
			}
			catch (PortalObjectNotFoundException e) 
			{
				// ignore if property is not present
			}
		}
	}
}
